package com.vfa.test;

import java.util.ArrayList;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.vfa.vocaburay.ExportQuestionToCsvFile;
import com.vfa.vocaburay.ImportQuestion;
import com.vfa.vocaburay.ImportQuestionFileCSV;
import com.vfa.vocaburay.R;

public class ListQuestion extends Activity{
	
	ListView listquestion;
	ArrayList<QuestionE> arrlistquestion;
	QuestionAdapter adapter;
	QuestionData data;
	QuestionE questionitem;
	
	CharSequence[] items = {"Delete"};
	String messageDialog="";
	private int questionid;
	private String question="";
	private String rightanswer="";
	int flagdialog=0;
	private Bundle mbundle;
	private String catagoryname, strbutton="";
	
	Utility util;
	DataHelperTest datahelp;
	
	private Button btnAdd, btnPre,btnNext;
	private TextView tv_title;
	
	private static final String TITLE_LISTQUESTION ="List Question  ";
	private static final String TITLE_QUESTIONINCATAGORY ="Question in Level ";
	
	private static final String btn_INSERT_QUESTION ="Insert Question";
	private static final String btn_ADD_QUESTION ="Add Question";
	private static final String btn_OK ="Add";
	private String flagbutton="";
	
	private int startpoint=0;
	private int numofstep = 10;
	private int endpoint = startpoint+numofstep;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.listquestion);
		

		btnAdd = (Button)findViewById(R.id.btn_addQuestion);
		btnPre = (Button)findViewById(R.id.btn_preQuestion);
		btnNext = (Button)findViewById(R.id.btn_nextQuestion);
		Button btnExportQuestion = (Button) findViewById(R.id.btExportQuestion);
		btnExportQuestion.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(ListQuestion.this, ExportQuestionToCsvFile.class);
				startActivity(i);
				ListQuestion.this.finish();		
			}
		});
		
		tv_title = (TextView)findViewById(R.id.textView_titleListQuestion);
		listquestion = (ListView)findViewById(R.id.listView_QuestionList);
		
		tv_title.setText(TITLE_LISTQUESTION);
		
		// khoi tao list question
		arrlistquestion = new ArrayList<QuestionE>();
		data = new QuestionData(this);
		ShowData();
		
		//set onclick for list
		listquestion.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterview, View arg1, int position,
					long arg3) {
				long rowIndex = adapterview.getItemIdAtPosition(position)  ;
				String text ="ItemI: "+ String.valueOf(rowIndex);	
				questionitem = arrlistquestion.get((Integer)position);
				question = questionitem.getQuestion().toString();
				questionid = questionitem.getQuestionId();
				QuestionDetail();
			}
		});
		
		listquestion.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> adapterview, View arg1,
					int position, long arg3) {
				questionitem = arrlistquestion.get((Integer)position);
				questionid = questionitem.getQuestionId();
				showDialog(2);
				return false;
			}
		});
		
		//listquestion.setHorizontalFadingEdgeEnabled(true);
		listquestion.setHorizontalScrollBarEnabled(true);
		listquestion.setOnTouchListener(onTouch_ListQuestion);
		
		
		btnAdd.setOnClickListener(tobtnAdd_listener);
		btnPre.setOnClickListener(tobtnPre_listener);
		btnNext.setOnClickListener(tobtnNext_listener);
	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Log.i("thong bao", "onStart!");
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.i("thong bao", "onResume!");
		adapter.notifyDataSetChanged();
		listquestion.setAdapter(adapter);
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		try {
			datahelp.CloseData();
		} catch (Exception e) {
			System.out.println("Can not close database! ");
		}
		
	}
	public void ShowData(){
		mbundle = this.getIntent().getExtras();
		//System.out.println(" day la bundle  " +mbundle);
		if (mbundle ==null) {
			System.out.println(" day la bundle  " +mbundle);
			ShowAllData();
		}
		else{
			if(mbundle.getInt("flagactivity")==1){
				catagoryname = mbundle.getString("catagoryname");
				//btnAdd.setText(btn_ADD_QUESTION);
				ShowDataByCata();
			}
		}
		
		
	}
	
	private void ShowAllData(){
		//arrlistquestion = data.getQuestion(4);
		arrlistquestion = data.getQuestionLimit(startpoint, numofstep);
		if(arrlistquestion.size()!=0){
		adapter = new QuestionAdapter(this, R.layout.test_item, arrlistquestion);
		
		adapter.setNoquestion(startpoint);
		
		listquestion.setAdapter(adapter);
		}
	}
	private void ShowDataByCata(){
		arrlistquestion = data.getQuestion(catagoryname);
		tv_title.setText(TITLE_QUESTIONINCATAGORY+ catagoryname);
		
		adapter = new QuestionAdapter(this, R.layout.test_item, arrlistquestion);
		
		adapter.setNoquestion(startpoint);
		
		listquestion.setAdapter(adapter);
		btnAdd.setContentDescription(btn_ADD_QUESTION);
	}
	
	private void ShowDataByCheckBox(){
		//arrlistquestion = data.getQuestion(4);
		arrlistquestion = data.getQuestionLimit(startpoint, numofstep);
		adapter = new QuestionAdapter(this, R.layout.test_item, arrlistquestion);
		adapter.showCheckBox(true);
		
		adapter.setNoquestion(startpoint);
		
		listquestion.setAdapter(adapter);
		
	}
	
	   @Override
		protected Dialog onCreateDialog(int id) {
			// TODO Auto-generated method stub
			//return super.onCreateDialog(id);
			   AlertDialog.Builder dialog =new AlertDialog.Builder(this);
			switch (id) {
			case 0:
				//return new AlertDialog.Builder(this)
				dialog.setTitle("Please Select option!");
				dialog.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						
							if(items[which].toString().equals("View detail")){
								flagdialog =1;
								QuestionDetail();
							}
							else if (items[which].toString().equals("Delete")) {
								flagdialog =2;
								messageDialog = "Do you want to delete this question ?";
								showDialog(1);
							}
							else if (items[which].toString().equals("Update")) {
								flagdialog =3;
								messageDialog ="Do you want to update this question ?";
								showDialog(1);
							}
							dialog.dismiss();
						}
						
				});
				AlertDialog alert0 = dialog.create();
				alert0.show();
				break;
			case 1:
				dialog.setTitle(" Notice! ");
				dialog.setMessage(messageDialog);
				dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if(flagdialog ==2)
						{
							//DeleteQuestion(questionid);
						}
						if(flagdialog == 3)
						{
							
						}
					}
				});
				dialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
				AlertDialog alert1 = dialog.create();
				alert1.show();
				break;
				
			case 2:
				dialog.setTitle("Please Select option!");
				dialog.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						
							if (items[which].toString().equals("Delete")) {
								messageDialog ="Do you want to delete this question ?";
								showDialog(3);
							}
							dialog.dismiss();
						}
						
				});
				AlertDialog alert2 = dialog.create();
				alert2.show();
			
				break;
				
				
			case 3:
		    	 dialog.setTitle(" Notice! ");
					dialog.setMessage(messageDialog);
					dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							DeleteQuestion(questionid);

						}
					});
					dialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
					AlertDialog alert4 = dialog.create();
					alert4.show();
					break;
					
					
			}
			return null;
	   }//end dialog
	   
	   public void DeleteQuestion (int id ){
			if(id >0){
				data.DeleteQuestion(id);
				if(arrlistquestion.size() == 1)
				{
					doPrev();
				}
				else
					ShowData();
			}
		}
	   
	   public void QuestionDetail(){
		   Intent intentQuestionDetail = new Intent(this, QuestionDetail.class);
		   
		   intentQuestionDetail.putExtra("idquestion", questionid);
		   intentQuestionDetail.putExtra("question", question);
		   //intentQuestionDetail.putExtra("rightanswer", rightanswer);
		   
		   startActivity(intentQuestionDetail);
		   
		   ListQuestion.this.finish();
	   }
	   private void doPrev()
	   {
		   if(startpoint!=0){
				if(startpoint>numofstep){
				startpoint =  startpoint - numofstep;
				endpoint = endpoint - numofstep;
				}
				else {
					startpoint =  0;
					endpoint = numofstep;
				}
				
				System.out.println("startpoint " + startpoint);
				System.out.println("endpoint " + endpoint);
				
				if(strbutton.equals(btn_ADD_QUESTION)){
					   ShowDataByCheckBox();
				   }
				 else{
					 ShowAllData();
				 }
				
			}
	   }
	   private android.view.View.OnClickListener tobtnPre_listener = new android.view.View.OnClickListener(){

			@Override
			public void onClick(View v) {
				doPrev();
			}
		   };
	   
		   private void doNext(){
			   if (arrlistquestion.size() == numofstep) {
					startpoint = startpoint + numofstep;
					endpoint = endpoint+ numofstep;
					
					System.out.println("startpoint " + startpoint);
					System.out.println("endpoint " + endpoint);
					 if(strbutton.equals(btn_ADD_QUESTION)){
						   ShowDataByCheckBox();
					   }
					 else{
						 ShowAllData();
					 }
					
				}
		   }
		   private android.view.View.OnClickListener tobtnNext_listener = new android.view.View.OnClickListener(){

				@Override
				public void onClick(View v) {
					doNext();
				}
			   };
	  
	   private android.view.View.OnClickListener tobtnAdd_listener = new android.view.View.OnClickListener(){

		@Override
		public void onClick(View v) {
			OnClickButton();
		}
	   };
	   
	   	int xfirst;
		int xcurr;
	   private android.view.View.OnTouchListener onTouch_ListQuestion = new android.view.View.OnTouchListener() {
		
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			
			case MotionEvent.ACTION_DOWN:
				xfirst = (int) event.getX();
				System.out.println("xfirst = "+xfirst);
				break;

			case MotionEvent.ACTION_UP:
				xcurr = (int)event.getX();
				System.out.println("xcurr = "+xcurr);
				int lengthx = xcurr - xfirst;
				System.out.println("lengthx = " + lengthx);
				if(lengthx > listquestion.getWidth()/3)
				{
					System.out.println("listquestion.getWidth()/3 = " +listquestion.getWidth()/2);
					doNext();
				}
				
				if(lengthx < -listquestion.getWidth()/3)
				{
					System.out.println("listquestion.getWidth()/2 = " +listquestion.getWidth()/2);
					doPrev();
				}
				break;
			}
		return false;
		}
	};
	   
	   public void OnClickBtImportQuestion(View view)
	   {
		   Intent intentImport = new Intent(this, ImportQuestionFileCSV.class);
		   startActivity(intentImport);
		   ListQuestion.this.finish();
	   }
	   public void OnClickButton(){
		  strbutton =  btnAdd.getContentDescription().toString();
		 
		  
		   if (strbutton.equals(btn_INSERT_QUESTION)) {
			   Intent intentinsert = new Intent(this, InsertQuestion.class);
			   intentinsert.putExtra("flagbundle", 1);
			   startActivity(intentinsert);
			   ListQuestion.this.finish();
		   }
		   if(strbutton.equals(btn_ADD_QUESTION)){
			   
			   ShowDataByCheckBox();
			   btnAdd.setContentDescription(btn_OK);
		   }
		   if(strbutton.equals(btn_OK)){
			   for (int i = 0; i < arrlistquestion.size(); i++) {
				   questionitem = arrlistquestion.get(i);
					//question = questionitem.getQuestion().toString();
					questionid = questionitem.getQuestionId();
					if(questionitem.isChecked()){
						data.InsertQuestionInCata(catagoryname, questionid);
					}
			   }
			   ShowDataByCata();
			   
		   }
		   
	   }
	   
	 /*  class MyGestureListener extends SimpleOnGestureListener implements OnTouchListener
	    {
	        Context context;
	        GestureDetector gDetector;

	        public MyGestureListener()
	        {
	            super();
	        }

	        public MyGestureListener(Context context) {
	            this(context, null);
	        }

	        public MyGestureListener(Context context, GestureDetector gDetector) {

	            if(gDetector == null)
	                gDetector = new GestureDetector(context, this);

	            this.context = context;
	            this.gDetector = gDetector;
	        }


	        @Override
	        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

	            return super.onFling(e1, e2, velocityX, velocityY);
	        }

	        @Override
	        public boolean onSingleTapConfirmed(MotionEvent e) {

	            return super.onSingleTapConfirmed(e);
	        }





	        public boolean onTouch(View v, MotionEvent event) {

	            // Within the MyGestureListener class you can now manage the event.getAction() codes.

	            // Note that we are now calling the gesture Detectors onTouchEvent. And given we've set this class as the GestureDetectors listener 
	            // the onFling, onSingleTap etc methods will be executed.
	        	System.out.println("gDetector.onTouchEvent(event); = "+ gDetector.onTouchEvent(event));
	            return gDetector.onTouchEvent(event);
	        }


	        public GestureDetector getDetector()
	        {
	            return gDetector;
	        }       
	    }*/
}//end class
